package cn.lml.lession.user.controller;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.lml.lession.user.model.User;
import cn.lml.lession.user.service.UserService;

@RestController
@RequestMapping("/user")
public class UserController {

	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	@Autowired
	private UserService userService;

	@PostMapping(value = "/save")
	public Map<String, Object> save(User user) {
		logger.info("保存数据 " + user);
		Integer uid = user.getUid();
		if (uid == null) {
			user.setUid((int)(99999000+Math.round(Math.random()*1000)+Math.round(Math.random()*100)+Math.round(Math.random()*10)));
			userService.insertUser(user);
		} else {
			userService.updateByUid(user);
		}
		Map<String, Object> responseMap = new HashMap<String, Object>();
		responseMap.put("state", 1);
		responseMap.put("msg", "保存成功");
		return responseMap;
	}

	@PostMapping(value = "/delete")
	public Map<String, Object> delete(@RequestParam(value = "uid") Integer uid) {
		logger.info("删除数据 " + uid);
		userService.deleteByUid(uid);
		Map<String, Object> responseMap = new HashMap<String, Object>();
		responseMap.put("state", 1);
		responseMap.put("msg", "删除成功");
		return responseMap;
	}

	@GetMapping(value = "/select")
	public User select(@RequestParam(value = "uid") Integer uid) {
		logger.info("查询数据 " + uid);
		return userService.selectByUid(uid);
	}

	@GetMapping(value = "/query")
	public Map<String,Object> query(@RequestParam(value = "page", defaultValue = "1") Integer page,@RequestParam(value = "size", defaultValue = "10") Integer size) {
		logger.info("分页查询数据 page=" + page + " size=" + size);
		Map<String, Object> cond = new HashMap<String, Object>();
		cond.put("start", (page - 1) * size);
		cond.put("end", page * size);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("count",userService.countUser(cond));
		resultMap.put("dataList",userService.queryUser(cond));
		return resultMap;
	}
	

	@GetMapping(value = "/findByUsername")
	public User findByUsername(@RequestParam(value = "username") String username) {
		logger.info("根据名称查询用户 " + username);
		return userService.findByUsername(username);
	}
	
}

